/*
48.旋转图像
将图像顺时针旋转 90 度。
给定 matrix =
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],
原地旋转输入矩阵，使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
 */

/**
 * @param {number[][]} matrix
 * @return {number[][]}
 */
function rotate (matrix) {
  if (!matrix.length || !matrix[0].length) {
    return [[]]
  }
  let top = 0
  let left = 0
  let right = matrix[0].length - 1
  let bottom = matrix.length - 1
  while (left < right && top < bottom) {
    _rotateEdge(matrix, top++, left++, bottom--, right--)
  }
}

// 边界旋转
function _rotateEdge (matrix, top, left, bottom, right) {
  const steps = right - left
  for (let i = 0; i < steps; i++) {
    const temp = matrix[top][left + i]
    matrix[top][left + i] = matrix[bottom - i][left]
    matrix[bottom - i][left] = matrix[bottom][right - i]
    matrix[bottom][right - i] = matrix[top + i][right]
    matrix[top + i][right] = temp
  }
}

const matrix = [
  [5, 1, 9, 11],
  [2, 4, 8, 10],
  [13, 3, 6, 7],
  [15, 14, 12, 16]
]

console.log(rotate(matrix))
